<template>
  <div>
    <el-button type="primary" @click="handleAddUser">添加用户</el-button>
    <el-table :data="users" style="width: 100%" stripe>
      <el-table-column prop="name" label="用户名" width="180" />
      <el-table-column prop="email" label="电子邮件" width="250" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="mini" @click="handleEditUser(row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDeleteUser(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" title="编辑用户">
      <el-form :model="currentUser">
        <el-form-item label="用户名">
          <el-input v-model="currentUser.name" />
        </el-form-item>
        <el-form-item label="电子邮件">
          <el-input v-model="currentUser.email" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUser">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const users = ref([
      { name: '用户1', email: 'user1@example.com' },
      { name: '用户2', email: 'user2@example.com' },
    ]);
    const dialogVisible = ref(false);
    const currentUser = ref({ name: '', email: '' });

    const handleAddUser = () => {
      currentUser.value = { name: '', email: '' };
      dialogVisible.value = true;
    };

    const handleEditUser = (user) => {
      currentUser.value = { ...user };
      dialogVisible.value = true;
    };

    const handleDeleteUser = (user) => {
      users.value = users.value.filter(u => u !== user);
    };

    const handleSaveUser = () => {
      if (currentUser.value.name && currentUser.value.email) {
        if (users.value.some(u => u.name === currentUser.value.name)) {
          users.value = users.value.map(u => (u.name === currentUser.value.name ? currentUser.value : u));
        } else {
          users.value.push(currentUser.value);
        }
        dialogVisible.value = false;
      }
    };

    return {
      users,
      dialogVisible,
      currentUser,
      handleAddUser,
      handleEditUser,
      handleDeleteUser,
      handleSaveUser,
    };
  },
};
</script>

<style scoped>
.el-table {
  margin-top: 20px;
}
</style>
